<script setup>
import {ref, onMounted} from "vue";
import {useRouter} from "vue-router";
import {Search, Tickets} from "@element-plus/icons-vue";
import {fetchBrandList} from "@/api/brand.js";
import {
  fetchProductList, fetchSimpleList,
  updateDeleteStatus, updateNewStatus,
  updateProRecommendStatus, updatePublishStatus,
} from "@/api/product.js";
import {fetchSkuList, updateSku} from "@/api/skuStock.js";
import {fetchListWithChildren} from "@/api/productCate.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {fetchProductAttrList} from "@/api/productAttr.js";

const router = useRouter();

// TODO: 页面加载完成后获取数据
onMounted(() => {
  getProductList();
  getBrandList();
  getProductCateList();
})

// TODO：顶部筛选条件
const formRef = ref("")
const searchForm = ref({
  productName: "",
  productNo: "",
  productCategory: "",
  productBrand: "",
  productStatus: "",
  productAudit: ""
});

// TODO:搜索按钮
const handleSearch = () => {
  // 更新 listQuery 以匹配搜索条件
  listQuery.keyword = searchForm.value.productName || searchForm.value.productNo;
  listQuery.productCategoryId = searchForm.value.productCategory[searchForm.value.productCategory.length - 1] || null;
  listQuery.brandId = searchForm.value.productBrand || null;
  listQuery.publishStatus = searchForm.value.productStatus !== "" ? parseInt(searchForm.value.productStatus) : null;
  listQuery.verifyStatus = searchForm.value.productAudit !== "" ? parseInt(searchForm.value.productAudit) : null;
  // 调用 getProductList 函数以获取新的商品列表
  getProductList();
}

// TODO：重置搜索条件
const handleResetSearch = () => {
  searchForm.value = {
    productName: "",
    productNo: "",
    productCategory: "",
    productBrand: "",
    productStatus: "",
    productAudit: ""
  };
  // 重新获取商品列表
  getProductList();
}
const publishStatusOptions = [
  {label: "上架", value: 1},
  {label: "下架", value: 0}
]
const verifyStatusOptions = [
  {label: "审核通过", value: 1},
  {label: "未审核", value: 0}
]

// TODO: 选项商品分类数据
const productCateOptions = ref([]);
const getProductCateList = async () => {
  const res = await fetchListWithChildren();
  const result = res.data.data
  for (let i = 0; i < result.length; i++) {
    let children = []
    if (result[i].children !== null && result[i].children.length > 0) {
      for (let j = 0; j < result[i].children.length; j++) {
        children.push({
          label: result[i].children[j].name,
          value: result[i].children[j].id
        })
      }
      productCateOptions.value.push({
        label: result[i].name,
        value: result[i].id,
        children: children
      })
    }
  }
}

// TODO: 选项商品品牌数据
const brandListOptions = ref([]);
const getBrandList = async () => {
  const res = await fetchBrandList({
    pageSize: 100,
    pageNum: 1,
  });
  brandListOptions.value = res.data.data.list;
  for (let i = 0; i < res.data.data.length; i++) {
    brandListOptions.value.push({
      label: res.data.data[i].name,
      value: res.data.data[i].id
    })
  }
}

// TODO: 底部商品列表数据（参数）
const defaultListQuery = {
  keyword: null,
  pageNum: 1,
  pageSize: 5,
  publishStatus: null,
  verifyStatus: null,
  productSn: null,
  productCategoryId: null,
  brandId: null
};
const total = ref(0)
const listQuery = Object.assign({}, defaultListQuery) // 深拷贝默认查询条件
const productList = ref([]);
const getProductList = async () => {
  const res = await fetchProductList(listQuery);
  productList.value = res.data.data.list;
  total.value = res.data.data.total;
};

// TODO: 上架/下架
const handlePublishStatusChange = (row) => {
  let ids = [];
  ids.push(row.id);
  upOrDownStatus(ids, row.publishStatus)
}
const upOrDownStatus = (ids, publishStatus) => {
  let params = new URLSearchParams();
  params.append("ids", ids);
  params.append("publishStatus", publishStatus);
  updatePublishStatus(params).then((res) => {
    ElMessage.warning(res.data.message);
    ElMessage.success("操作成功");
    getProductList();
  })
}

// TODO: 新品/非新品
const handleNewStatusChange = (row) => {
  let ids = [];
  ids.push(row.id);
  newProductStatus(ids, row.newStatus)
}
const newProductStatus = (ids, newStatus) => {
  let params = new URLSearchParams();
  params.append("ids", ids);
  params.append("newStatus", newStatus);
  updateNewStatus(params).then((res) => {
    ElMessage.warning(res.data.message);
    ElMessage.success("修改成功");
    getProductList();
  })
}

// TODO: 推荐/不推荐
const handleRecommendStatusChange = (row) => {
  let ids = [];
  ids.push(row.id);
  recommendProductStatus(ids, row.recommandStatus)
}
const recommendProductStatus = (ids, recommendStatus) => {
  let params = new URLSearchParams();
  params.append("ids", ids);
  params.append("recommendStatus", recommendStatus);
  updateProRecommendStatus(params).then((res) => {
    ElMessage.warning(res.data.message);
    ElMessage.success("修改成功");
    getProductList();
  })
}

// TODO: 新增商品
const handleAddProduct = () => {
  router.push("/product/add");
}


// TODO: 库存弹窗
const editSkuInfo = ref({
  dialogVisible: false,
  productId: null,
  productSn: '',
  productAttributeCategoryId: null,
  stockList: [],
  productAttr: [],
  keyword: null
})
const getProductSkuSp = (row, index) => {
  let spData = JSON.parse(row.spData);
  if (spData!== null && index < spData.length) {
    return spData[index].value;
  } else {
    return null;
  }
}
const handleSearchEditSku = () => {
  fetchSkuList(editSkuInfo.value.productId,{keyword:editSkuInfo.value.keyword}).then((res) => {
    editSkuInfo.value.stockList = res.data.data
    console.log(res.data.data)
  })
}

// TODO: SKU库存
const handleShowSkuEditDialog = (row) => {
  editSkuInfo.value.dialogVisible = true
  editSkuInfo.value.productId = row.id
  editSkuInfo.value.productSn = row.productSn
  editSkuInfo.value.productAttributeCategoryId = row.productAttributeCategoryId
  editSkuInfo.value.keyword = null
  fetchSkuList(row.id,{keyword:editSkuInfo.value.keyword}).then((res) => {
    editSkuInfo.value.stockList = res.data.data
    console.log(res.data.data)
  })
  if(row.productAttributeCategoryId!=null) {
    fetchProductAttrList(row.productAttributeCategoryId,{type:0}).then((res) => {
      console.log(res.data.data.list)
      editSkuInfo.value.productAttr = res.data.data.list
    })
  }

}

// TODO: 审核详情
const handleShowVerifyDetail = (index, row) => {
  console.log(row);
}

// TODO: 查看按钮
const handleShowProduct = (index, row) => {
  console.log(row);
}

// TODO: 编辑按钮
const handleUpdateEditProduct = (row) => {
  router.push({path: "/product/add", query: {id: row.id}});
}

// TODO: 日志按钮
const handleShowLog = (index, row) => {
  console.log(row);
}

// TODO: 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm("是否确定删除该商品?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    let ids = []
    ids.push(row.id)
    upDeleteStatus(1, ids)
  }).catch(() => {
    console.log("取消删除");
  })
}
const upDeleteStatus = (deleteStaus, ids) => {
  let params = new URLSearchParams();
  params.append("ids", ids);
  params.append("deleteStatus", deleteStaus);
  updateDeleteStatus(params).then((res) => {
    ElMessage.warning(res.data.message);
    ElMessage.success("删除成功");
  })
}

// TODO: 批量操作
const operateType = ref("");
const operates = [
  {label: "商品上架", value: "publishOn"},
  {label: "商品下架", value: "publishOff"},
  {label: "设为推荐", value: "recommendOn"},
  {label: "取消推荐", value: "recommendOff"},
  {label: "设为新品", value: "newOn"},
  {label: "取消新品", value: "newOff"},
  {label: "转移到分类", value: "transferCategory"},
  {label: "移入回收站", value: "recycle"}
]
const handleBatchOperate = () => {
  console.log(operateType.value);
}

// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageSize = size;
  getProductList();
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getProductList();
}
</script>

<template>
  <div class="product-list">
    <!-- 顶部搜索区域-->
    <div class="top-bar">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form ref="formRef" :inline="true" v-model="searchForm" label-width="100px">
          <el-form-item label="商品名称:">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品货号:">
            <el-input v-model="searchForm.productNo" placeholder="请输入商品货号" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品分类:">
            <el-cascader
                :options="productCateOptions"
                v-model="searchForm.productCategory"
                placeholder="请选择商品分类"
                clearable
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="商品品牌:">
            <el-select v-model="searchForm.productBrand" placeholder="请选择商品品牌" clearable>
              <el-option v-for="brand in brandListOptions" :key="brand.id" :label="brand.name"
                         :value="brand.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上架状态:">
            <el-select v-model="searchForm.productStatus" placeholder="请选择上架状态" clearable>
              <el-option v-for="item in publishStatusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态:">
            <el-select v-model="searchForm.productAudit" placeholder="请选择审核状态" clearable>
              <el-option v-for="item in verifyStatusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 中部添加按钮 -->
    <div class="center-bar">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
      <el-button type="primary" icon="plus" @click="handleAddProduct()" style="margin-left: 20px;">
        添加商品
      </el-button>
    </div>
    <!-- 底部商品列表 -->
    <div class="bottom-bar">
      <el-table :data="productList" style="width: 100%;" border>
        <el-table-column type="selection" width="80" align="center"></el-table-column>
        <el-table-column label="商品编号" width="150" align="center">
          <template #default="{row}">{{ row.id }}</template>
        </el-table-column>
        <el-table-column label="商品图片" width="250" align="center">
          <template #default="{row}">
            <img :src="row.pic" alt="" style="height: 80px;">
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template #default="{row}">
            <p>品牌：{{ row.brandName }}</p>
            <p>{{ row.name }}</p>
          </template>
        </el-table-column>
        <el-table-column label="价格/货号" width="200" align="center">
          <template #default="{row}">
            <p>价格：￥{{ row.price }}</p>
            <p>货号：{{ row.productSn }}</p>
          </template>
        </el-table-column>
        <el-table-column label="商品标签" width="200" align="center">
          <template #default="{row}">
            <p>上架：
              <el-switch
                  v-model="row.publishStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handlePublishStatusChange(row)">
              </el-switch>
            </p>
            <p>新品：
              <el-switch
                  v-model="row.newStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleNewStatusChange(row)">
              </el-switch>
            </p>
            <p>推荐：
              <el-switch
                  v-model="row.recommandStatus"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleRecommendStatusChange(row)">
              </el-switch>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="商品排序" width="150" align="center">
          <template #default="{row}">
            {{ row.sort }}
          </template>
        </el-table-column>
        <el-table-column label="SKU库存" width="150" align="center">
          <template #default="{row}">
            <el-button type="primary" @click="handleShowSkuEditDialog(row)" circle icon="edit"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品销量" width="150" align="center">
          <template #default="{row}">
            {{ row.sale }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="150" align="center">
          <template #default="{row}">
            {{ row.verifyStatus === 1 ? '审核通过' : '未审核' }}
            <p>
              <el-button
                  type="text"
                  @click="handleShowVerifyDetail(row.index, row)">审核详情
              </el-button>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{row}">
            <div class="operation-btns">
              <p>
                <el-button @click="handleShowProduct(row)">查看</el-button>
                <el-button type="primary" @click="handleUpdateEditProduct(row)">编辑</el-button>
              </p>
              <p>
                <el-button @click="handleShowLog(row)">日志</el-button>
                <el-button type="danger" @click="handleDelete(row)">删除</el-button>
              </p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <div class="page-bar">
      <div class="select-type">
        <span>批量操作：</span>
        <el-select v-model="operateType" placeholder="请选择操作">
          <el-option
              v-for="item in operates"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button
            style="margin-left: 20px"
            @click="handleBatchOperate()"
            type="primary"
            size="small">
          确定
        </el-button>
      </div>
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>

  <!-- 库存弹窗 -->
  <el-dialog
      title="编辑货品信息:"
      v-model="editSkuInfo.dialogVisible"
      width="50%">
    <span class="product-num">商品货号：</span>
    <span class="product-num">{{ editSkuInfo.productSn }}</span>
    <el-input placeholder="按sku编号搜索" v-model="editSkuInfo.keyword"
              clearable style="width: 50%;margin-left: 20px">
      <template #append>
        <el-button icon="search" @click="handleSearchEditSku"></el-button>
      </template>
    </el-input>
    <el-table style="margin-top: 20px"
              :data="editSkuInfo.stockList"
              border>
      <el-table-column
          label="SKU编号"
          align="center">
        <template #default="{row}">
          <el-input v-model="row.skuCode"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          v-for="(item,index) in editSkuInfo.productAttr"
          :label="item.name"
          :key="item.id"
          align="center">
        <template #default="{row}">
          {{ getProductSkuSp(row, index) }}
        </template>
      </el-table-column>
      <el-table-column
          label="销售价格"
          align="center">
        <template #default="{row}">
          <el-input v-model="row.price">
            <template #prepend>￥</template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column
          label="商品库存"
          align="center">
        <template #default="{row}">
          <el-input v-model="row.stock"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          label="库存预警值"
          align="center">
        <template #default="{row}">
          <el-input-number v-model="row.lowStock" />
<!--          <el-input type="number" v-model="row.lowStock"></el-input>-->
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 20px;">
      <el-button type="primary" @click="handleSaveSkuInfo">保存</el-button>
      <el-button type="danger" plain @click="editSkuInfo.dialogVisible = false">取消</el-button>
    </div>


  </el-dialog>

</template>

<style scoped lang="scss">
.product-list {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top-bar {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin-top: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .center-bar {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .bottom-bar {
    //border: 1px solid #d5d5d5;

    .operation-btns {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      p {
        width: 100%;
        margin: 8px 0;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 10px 20px;
    border: 1px solid #d5d5d5;

    .select-type {
      width: 400px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    span {
      width: 150px;
    }
  }
}

.product-num {
  font-size: 16px;
  color: #F56C6C;
  font-weight: bold;
}
</style>